package com.sky.task;


import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 订单超时订单处理
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("开始进行支付超时订单处理:{}", LocalDateTime.now());
        LocalDateTime time=LocalDateTime.now().plusMinutes(-15);//再改时间前未支付已超时
        List<Orders> ordersList=orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,time);
        if(ordersList!=null&&ordersList.size()>0){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);//已经取消
                orders.setCancelReason(MessageConstant.PAYMENT_TIMEOUT_AUTO_CANCEL);
                orders.setCancelTime(LocalDateTime.now());
                //更新订单
                orderMapper.update(orders);
            });
        }

    }
    /**
     * 派送中状态订单处理
     */
    @Scheduled(cron="0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("开始进行未完成订单状态处理:{}",LocalDateTime.now());
        LocalDateTime time=LocalDateTime.now().plusMinutes(-60);//处理前一天所有订单
        List<Orders> ordersList=orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS,time);
        if(ordersList!=null&&ordersList.size()>0){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);//已完成
                //更新订单
                orderMapper.update(orders);
            });
        }

    }




}
